#encoding:gbk
'''
小市值策略
'''
import pandas as pd
import numpy as np
import talib as tl
import datetime
import time


def quote_callback(s):
	def callback(data):
		print(s,data)
		return
	return callback




def init(ContextInfo):
	'''
	ContextInfo.buy = True
	ContextInfo.sell = False
	index_universe = ['000991.SH'] 
	index_stocks = []
	for index in index_universe:
		#print(index)
		for stock in ContextInfo.get_sector(index):
			stock_Name = ContextInfo.get_stock_name(stock)
			#print(stock+':'+stock_Name)
			index_stocks.append(stock)
	'''
	#ContextInfo.subscribe_quote("600000.SH","tick","none",quote_callback('600000.SH'))
	#print(index_stocks)
	#ContextInfo.set_universe(index_stocks)
	#print(ContextInfo.get_sector('000905.SH'))
	#print( ContextInfo.get_industry('CSRC采矿业'))
	
	index = ContextInfo.barpos
	realtime = ContextInfo.get_bar_timetag(index)
	
	ContextInfo.choicenum =1
	ContextInfo.days=0
	ContextInfo.runned_years = []
	ContextInfo.runned_seasons = []
	 # 现在应该持有的仓位, 因为可能停牌导致卖出不成功, 跟实际持仓可能不一样
	ContextInfo.stocks_to_hold = 0

    # 调仓频率
	## week, month, season,year,day
	ContextInfo.periods = 'year' 
	# 是否止损
	ContextInfo.should_stop_loss = False #True:开启止损,False:关闭止损
	
	print('init end')
		
def handlebar(ContextInfo):
	daily(ContextInfo)


	
	
def daily(ContextInfo):
	if (ContextInfo.periods == 'day'):
		rebalance(ContextInfo)
	ContextInfo.days += 1



# 调整
def rebalance(ContextInfo):
	print('rebalance at s')
	#% ContextInfo.current_dt
	'''
	# 设置沪深两市所有股票为股票池
	scu0 = get_index_stocks('000001.XSHG')
	scu3 = get_index_stocks('399106.XSHE')
	scu = scu0+scu3

	# scu = scu[:10]
	set_universe(scu)

	date=context.current_dt.strftime("%Y-%m-%d")

	# 选出低市值的股票，buylist
	df = 

	buylist =unpaused(list(df['code']))
	g.stocks_to_hold = buylist=buylist[:g.choicenum]

	clean_stocks_to_sell(context)

	# 等权重买入buylist中的股票
	position_per_stk = context.portfolio.cash/g.choicenum
	closes = history(1, '1d', 'price', df=False)
	for stock in buylist:
		close = closes[stock][-1]
		if not isnan(close):
			amount = int(position_per_stk/close)
			order(stock, +amount)
	set_universe(g.stocks_to_hold)
	'''
